import EventCenter from "../../TFrame/script/helper/EventCenter";
import EventNames from "../EventNames";
import { ActionType } from "../net/Enum";
import ServiceLogic from "../net/ServerLogic";
import Util from "../../../StartAb/Util";
import CoinSystem from "./CoinSystem";
import DailyTaskSystem from "./DailyTaskSystem";
import IAPSystem from "./IAPSystem";
import TurnTableSystem from "./TurnTableSystem";

const {ccclass, property} = cc._decorator;

/**
 * 运行中，检测新的一天到来
 * 启动时，检测是否是新的一天
 */
@ccclass
export default class TimeSystem extends cc.Component {

    keyLastLoginTs = "keyLastLoginTs";
    lastTimeStamp = 0;

    _lastDay = 0;

    onLoad () {
        cc.game.addPersistRootNode(this.node);
        DailyTaskSystem.init();
        this.checkIsNewDayFromLastLogin();
       
        cc.game.on(cc.game.EVENT_HIDE, ()=>{
            cc.sys.localStorage.setItem(this.keyLastLoginTs, (new Date()).getTime());
            DailyTaskSystem.persist();
            ServiceLogic.action(ActionType.ActionBackGround, {})
            // cc.log("hide hide");
        }, this)
        cc.game.on(cc.game.EVENT_SHOW, ()=>{
            this.checkIsNewDayFromLastLogin();
            // ServiceLogic.action(ActionType.ActionEnterForeGround, {})
            // cc.log("show show")
        }, this)

        this._lastDay = (new Date()).getDate();
    }

    checkIsNewDayFromLastLogin() {
        this.lastTimeStamp = parseInt(cc.sys.localStorage.getItem(this.keyLastLoginTs)) || 0;
        let daydiff = Util.getDayDiff(new Date(this.lastTimeStamp), new Date());
        if(daydiff > 0) {
            DailyTaskSystem.resetTaskListForNewDay();
        }
    }

    start () {
        EventCenter.on(EventNames.IAPSuccess, (iapId) => {
            //此处负责加金币逻辑 shoplayer负责飞金币动画
            let coinNum = IAPSystem.getIAPCoinNum(iapId);
            if(coinNum > 0) {
                console.log("ISHOP success:" + iapId + "," + coinNum)
                CoinSystem.addCoin(coinNum);
            }
        }, this)

        this.schedule(this.perSecond, 1.0);
    }

    perSecond() {
        let now = new Date();
        if(now.getDate() != this._lastDay) {
            DailyTaskSystem.resetTaskListForNewDay();
            TurnTableSystem.itsANewDay();
            this._lastDay = now.getDate();
        }
    }
}
